<template>
  <div class="login-container">
    <!-- 背景动画 -->
    <div class="background-animation"></div>
    
    <div class="login-wrapper">
      <div class="login-box">
        <!-- Logo区域 -->
        <div class="login-logo">
          <div class="logo-circle">
            <el-icon class="logo-icon"><HomeFilled /></el-icon>
          </div>
          <h1>IoT 智能家居</h1>
          <p>连接未来，智享生活</p>
        </div>
        
        <!-- 登录/注册标签页 -->
        <el-tabs v-model="activeTab" class="login-tabs" stretch>
          <!-- 登录标签 -->
          <el-tab-pane label="登录" name="login">
            <el-form 
              ref="loginFormRef" 
              :model="loginForm" 
              :rules="loginRules" 
              label-width="0px"
              @submit.prevent="handleLogin"
            >
              <el-form-item prop="username">
                <el-input 
                  v-model="loginForm.username" 
                  placeholder="请输入用户名" 
                  prefix-icon="User"
                  clearable
                  size="large"
                  @keyup.enter="handleLogin"
                />
              </el-form-item>
              
              <el-form-item prop="password">
                <el-input 
                  v-model="loginForm.password" 
                  type="password" 
                  placeholder="请输入密码" 
                  prefix-icon="Lock"
                  show-password
                  size="large"
                  @keyup.enter="handleLogin"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  class="login-button" 
                  @click="handleLogin"
                  :loading="loginLoading"
                  size="large"
                  round
                >
                  {{ loginLoading ? '登录中...' : '登录' }}
                </el-button>
              </el-form-item>
              
              <div class="login-options">
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                <el-link type="primary" @click="goToResetPassword">忘记密码?</el-link>
              </div>
            </el-form>
          </el-tab-pane>
          
          <!-- 注册标签 -->
          <el-tab-pane label="注册" name="register">
            <el-form 
              ref="registerFormRef" 
              :model="registerForm" 
              :rules="registerRules" 
              label-width="0px"
              @submit.prevent="handleRegister"
            >
              <el-form-item prop="username">
                <el-input 
                  v-model="registerForm.username" 
                  placeholder="请输入用户名" 
                  prefix-icon="User"
                  clearable
                  size="large"
                />
              </el-form-item>
              
              <el-form-item prop="nickname">
                <el-input 
                  v-model="registerForm.nickname" 
                  placeholder="请输入昵称" 
                  prefix-icon="User"
                  clearable
                  size="large"
                />
              </el-form-item>
              
              <el-form-item prop="password">
                <el-input 
                  v-model="registerForm.password" 
                  type="password" 
                  placeholder="请输入密码" 
                  prefix-icon="Lock"
                  show-password
                  size="large"
                />
              </el-form-item>
              
              <el-form-item prop="confirmPassword">
                <el-input 
                  v-model="registerForm.confirmPassword" 
                  type="password" 
                  placeholder="请确认密码" 
                  prefix-icon="Lock"
                  show-password
                  size="large"
                />
              </el-form-item>
              
              <el-form-item prop="email">
                <el-input 
                  v-model="registerForm.email" 
                  placeholder="请输入邮箱" 
                  prefix-icon="Message"
                  clearable
                  size="large"
                />
              </el-form-item>
              
              <el-form-item prop="phone">
                <el-input 
                  v-model="registerForm.phone" 
                  placeholder="请输入手机号" 
                  prefix-icon="Phone"
                  clearable
                  size="large"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  class="register-button" 
                  @click="handleRegister"
                  :loading="registerLoading"
                  size="large"
                  round
                >
                  {{ registerLoading ? '注册中...' : '注册' }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        
        <!-- 错误信息 -->
        <div class="message-area">
          <p class="error-message" v-if="errorMsg">{{ errorMsg }}</p>
          <p class="debug-info" v-if="debugMsg">调试信息：{{ debugMsg }}</p>
        </div>
      </div>
      
      <!-- 底部信息 -->
      <div class="login-footer">
        <p>© 2023 IoT 智能家居系统. 保留所有权利.</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const activeTab = ref('login')
const loginLoading = ref(false)
const registerLoading = ref(false)
const errorMsg = ref('')
const debugMsg = ref('')
const rememberMe = ref(false)

// 登录表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 登录表单数据
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

// 注册表单数据
const registerForm = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 组件挂载时恢复记住的用户名
onMounted(() => {
  if (rememberMe.value) {
    const savedUsername = localStorage.getItem('savedUsername')
    if (savedUsername) {
      loginForm.username = savedUsername
    }
  }
})

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true
      errorMsg.value = ''
      debugMsg.value = '开始登录请求...'
      
      try {
        // 发送登录请求
        const res = await axios.get('http://localhost:8082/login', {
          params: {
            username: loginForm.username,
            password: loginForm.password
          }
        })

        debugMsg.value = `后端返回: code=${res.data.code}, 用户=${res.data.data?.username || '空'}`
        console.log('完整响应:', res.data)

        // 判断登录结果
        if (res.data.code === 200 && res.data.data) {
          // 保存用户信息到localStorage
          localStorage.setItem('user', JSON.stringify(res.data.data))
          // 保存token到localStorage
          localStorage.setItem('token', res.data.data.token)
          
          // 如果选择了记住我，保存用户名
          if (rememberMe.value) {
            localStorage.setItem('savedUsername', loginForm.username)
          }
          
          ElMessage.success('登录成功')
          router.push('/home')
        } else {
          errorMsg.value = res.data.msg || '用户名或密码错误'
        }
      } catch (err) {
        console.error('登录请求失败:', err)
        debugMsg.value = `请求失败: ${err.message}`
        errorMsg.value = '连接后端失败，请检查服务是否启动'
      } finally {
        loginLoading.value = false
      }
    }
  })
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true
      errorMsg.value = ''
      debugMsg.value = '开始注册请求...'
      
      try {
        // 构造注册数据
        const registerData = {
          username: registerForm.username,
          nickname: registerForm.nickname,
          password: registerForm.password,
          email: registerForm.email,
          phone: registerForm.phone,
          isActive: true
        }
        
        // 发送注册请求
        const res = await axios.post('http://localhost:8082/register', registerData)
        
        debugMsg.value = `后端返回: code=${res.data.code}, 消息=${res.data.msg || '空'}`
        console.log('完整响应:', res.data)
        
        // 判断注册结果
        if (res.data.code === 200) {
          ElMessage.success('注册成功')
          // 清空注册表单
          Object.keys(registerForm).forEach(key => {
            registerForm[key] = ''
          })
          // 切换到登录标签
          activeTab.value = 'login'
        } else {
          errorMsg.value = res.data.msg || '注册失败'
        }
      } catch (err) {
        console.error('注册请求失败:', err)
        debugMsg.value = `请求失败: ${err.message}`
        errorMsg.value = '连接后端失败，请检查服务是否启动'
      } finally {
        registerLoading.value = false
      }
    }
  })
}

// 跳转到密码重置页面
const goToResetPassword = () => {
  router.push('/reset-password')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100vw;
  overflow: hidden;
  position: relative;
}

/* 背景动画 */
.background-animation {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(-45deg, #1e3c72, #2a5298, #2a5298, #1e3c72);
  background-size: 400% 400%;
  animation: gradientShift 15s ease infinite;
  z-index: -1;
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.login-wrapper {
  width: 100%;
  max-width: 450px;
  padding: 20px;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-box {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  padding: 40px 30px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
}

/* Logo区域 */
.login-logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo-circle {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}

.logo-icon {
  font-size: 40px;
  color: white;
}

.login-logo h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.login-logo p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

/* 标签页 */
.login-tabs {
  margin-bottom: 20px;
}

.login-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 30px;
}

/* 表单元素 */
.login-button,
.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

/* 登录选项 */
.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

/* 消息区域 */
.message-area {
  margin-top: 20px;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  text-align: center;
  margin: 0;
}

.debug-info {
  color: #909399;
  font-size: 12px;
  text-align: center;
  margin: 10px 0 0 0;
}

/* 底部信息 */
.login-footer {
  text-align: center;
  margin-top: 30px;
  color: rgba(255, 255, 255, 0.8);
}

.login-footer p {
  margin: 0;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-wrapper {
    padding: 10px;
  }
  
  .login-box {
    padding: 30px 20px;
  }
  
  .login-logo h1 {
    font-size: 24px;
  }
  
  .login-logo p {
    font-size: 14px;
  }
}
</style>